//
//  CCDBaseViewController.m
//  crowd
//
//  Created by 马腾飞 on 16/4/8.
//  Copyright © 2016年 caocaod.com. All rights reserved.
//

#import "CCDBaseViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>

@interface CCDBaseViewController ()<AMapLocationManagerDelegate,MAMapViewDelegate>
@property (strong, nonatomic)               AMapLocationManager *locationManager;
@property (strong, nonatomic)               MAMapView *mapView;
@property (strong, nonatomic)               NSString *aesString;
@end

@implementation CCDBaseViewController

-(UIStatusBarStyle) preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor yellowColor]];
//    [self initMapLocation];
}

//初始化MapLocation
- (void)initMapLocation {
    [AMapServices sharedServices].apiKey = AMapKey;
//    _mapView = [[MAMapView alloc] init];
//    _mapView.delegate = self;
//    _mapView.mapType = MAMapTypeStandard;
//    _mapView.language = MAMapLanguageZhCN;
//    _mapView.showsScale = NO;
//    [self.view addSubview:self.mapView];
//    _mapView.hidden = YES;
    
    _locationManager = [[AMapLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    _locationManager.distanceFilter = 10.0f;
    [_locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];
}

#pragma mark -_- AMapLocationManagerDelegate
//正确位置的回调
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
        NSLog(@"location:{lat:%f; lon:%f; accuracy:%f; course:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy,location.course);
}

//产生错误时产生的回调
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setBaseNavWithTitle:(NSString *)title imageName:(NSString *)imageName{
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    [titleLabel setFont:[UIFont systemFontOfSize:17]];
    [titleLabel setText:title];
    [titleLabel setTextColor:[UIColor whiteColor]];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [self.navigationItem setTitleView:titleLabel];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setFrame:CGRectMake(0, 0, 40, 44)];
    [leftBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [leftBtn setTitle:@"   " forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftBtn.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
    [leftBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBtnItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    [self.navigationItem setLeftBarButtonItem:leftBtnItem];

    if (([[[ UIDevice currentDevice ] systemVersion ] floatValue ]>= 7.0 ? 20 : 0 )) {
        UIBarButtonItem *negativeSpacer = [[ UIBarButtonItem alloc ] initWithBarButtonSystemItem : UIBarButtonSystemItemFixedSpace target : nil action : nil ];
        negativeSpacer. width = -5 ;//这个数值可以根据情况自由变化
        self.navigationItem.leftBarButtonItems = @[negativeSpacer, leftBtnItem];
    } else{
        self.navigationItem.leftBarButtonItem = leftBtnItem;
    }
}

- (void)backAction:(UIButton *)sender {
    NSLog(@"我是基类");
}

#pragma createAesKey
- (void)createAesKey {
    WS(weakSelf);
    if(UserValue(@"AESKey")) {
        self.aesString = UserValue(@"AESKey");
    }
    NSString *aesKey = [NSString getAuthcode];
    UserSetValueForKey(aesKey, @"ASEKey");
    NSLog(@"%@",aesKey);
    NSString *timeStr = [NSString getCurrentTime];
    NSDictionary *aesDic = @{
                             @"key":aesKey,
                             @"time":timeStr
                             };
    
    NSString *aesString = [NSString getJsonStringWithDic:aesDic];
    NSString *encString = [RSAUtil encryptString:aesString publicKey:UserValue(@"rsa_public_key")];
    
    NSString *baseUrl = @"http://serv.caocaod.com/app/main/createAesKey";
    NSDictionary *dict = UserValue(@"rsa_app_ver");
    NSDictionary *newDic = @{
                             @"verRsa":dict[@"verRsa"],
                             @"verApp":[NSString getAppVer],
                             @"app":@"com.caocaod.work",
                             @"platform":@"iOS",
                             @"rsa":encString
                             };
    
    [self postWithUrl:baseUrl params:newDic progressView:nil successBlock:^(id JSON) {
        NSDictionary *tempDic = JSON;
        if([tempDic[@"result"] integerValue] == 1) {
            NSString *string = tempDic[@"aes"];
            NSString *descString1 = [AESSecurityTool decryptAndBase64ToStringWithString:string];
            NSDictionary *cookieDic = [NSDictionary dictionaryWithJsonString:descString1];
            if(1 == [cookieDic[@"result"] integerValue]) {
                if(UserValue(@"cookie")) {
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cookie"];
                }
                UserSetValueForKey(cookieDic[@"cookie"], @"cookie");
            }
            NSLog(@"%@",tempDic);
            //如果成功
        }else {
            if(self.index <= 2) {
                    weakSelf.index ++;
                    [self createAesKey];
                } else {
                    [self.view makeToast:@"服务器异常，请稍候再试" duration:1.5 position:@"center"];
                    weakSelf.index = 0;
                }
            
            if(self.aesString) {
                UserSetValueForKey(self.aesString, @"AESKey");
            }
    
        }
    } faithBlock:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)getWithUrl:(NSString *)url params:(NSDictionary *)params progressView:(UIProgressView *)progressView successBlock:(SuccessBlock)httpSuccess faithBlock:(FaithBlock)httpFaith {
    [CCDHttpBaseTool getWithPath:url params:params progress:nil success:^(id JSON) {
        httpSuccess(JSON);
    } failure:^(NSError *error) {
        httpFaith(error);
    }];
    
}

- (void)postWithUrl:(NSString *)url params:(NSDictionary *)params progressView:(UIProgressView *)progressView successBlock:(SuccessBlock)httpSuccess faithBlock:(FaithBlock)httpFaith {
    [CCDHttpBaseTool postWithPath:url params:params progress:nil success:^(id JSON) {
        httpSuccess(JSON);
    } failure:^(NSError *error) {
        httpFaith(error);
    }];
}


//+ (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL fileName:(NSString *)fileName fileType:(NSString *)fileTye success:(void (^)(id responseObject))success fail:(void (^)())fail
//{
//    // 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    //@"http://localhost/demo/upload.php"
//    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        
//        //        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];
//        
//        // 要上传保存在服务器中的名称
//        // 使用时间来作为文件名 2014-04-30 14:20:57.png
//        // 让不同的用户信息,保存在不同目录中
//        //        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        //        // 设置日期格式
//        //        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//        //        NSString *fileName = [formatter stringFromDate:[NSDate date]];
//        
//        //@"image/png"
//        [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:fileTye error:NULL];
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if (success) {
//            success(responseObject);
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (fail) {
//            fail();
//        }
//    }];
//}


@end
